<template>
  <div class="app-container">
    <el-form
      :model="queryParams"
      ref="queryForm"
      size="small"
      :inline="true"
      v-show="showSearch"
      label-width="100px"
    >
      <el-form-item label="预约时间" prop="time">
        <el-date-picker
          v-model="time"
          style="width: 240px"
          :picker-options="pickerOptions"
          value-format="yyyy-MM-dd"
          type="daterange"
          @change="getTime"
          range-separator="-"
          start-placeholder="开始日期"
          end-placeholder="结束日期"
        ></el-date-picker>
      </el-form-item>
      <el-form-item>
        <el-button
          type="primary"
          icon="el-icon-search"
          size="mini"
          @click="handleQuery"
          v-hasPermi="['business:coupondetailed:query']"
          >搜索</el-button
        >
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery"
          >重置</el-button
        >
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <!-- <el-col :span="1.5">
        <el-button type="primary" plain icon="el-icon-plus" size="mini" @click="handleAdd" v-hasPermi="['system:user:add']">新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="success" plain icon="el-icon-edit" size="mini" :disabled="single" @click="handleUpdate" v-hasPermi="['system:user:edit']"
          >修改</el-button
        >
      </el-col>
      <el-col :span="1.5">
        <el-button type="danger" plain icon="el-icon-delete" size="mini" :disabled="multiple" @click="handleDelete" v-hasPermi="['system:user:remove']"
          >删除</el-button
        >
      </el-col> -->
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="el-icon-download"
          size="mini"
          @click="handleExport"
          v-hasPermi="['system:user:export']"
          >导出</el-button
        >
      </el-col>
      <right-toolbar
        :showSearch.sync="showSearch"
        @queryTable="getList"
      ></right-toolbar>
    </el-row>

    <el-table
      v-if="type != 'repurchaseRate'"
      v-loading="loading"
      :data="storeList"
      max-height="650px"
      @selection-change="handleSelectionChange"
    >
      <!-- <el-table-column type="selection" width="100" align="center" /> -->
      <el-table-column label="月份" align="center" prop="num" />
      <el-table-column label="总客数" align="center" prop="name" />
      <el-table-column label="回头客数" align="center" prop="couponTypeName" />
      <el-table-column label="新客数" align="center" prop="regionName" />
      <el-table-column label="回头客占比" align="center" prop="storeName" />
      <el-table-column label="新客占比" align="center" prop="userName" />
      <el-table-column label="复购订单数" align="center" prop="userTime" />
      <el-table-column label="总订单数" align="center" prop="userTime" />
      <el-table-column label="订单复购率" align="center" prop="userTime" />
    </el-table>
    <el-table
      v-else
      v-loading="loading"
      :data="storeList"
      max-height="650px"
      @selection-change="handleSelectionChange"
    >
      <!-- <el-table-column type="selection" width="100" align="center" /> -->
      <el-table-column label="月份" align="center" prop="num" />
      <el-table-column label="服务项目" align="center" prop="name" />
      <el-table-column label="服务次数" align="center" prop="couponTypeName" />
      <el-table-column label="复购率" align="center" prop="storeName" />
    </el-table>

    <pagination
      v-show="total > 0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改用户对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="500px" append-to-body>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import {
  listUser,
  getUser,
  delUser,
  addUser,
  updateUser,
} from "@/api/system/user";
import { fetchRegionList, fetchStoreList } from "@/api/system/orderList/order";

export default {
  name: "User",
  data() {
    return {
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 用户表格数据
      storeList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        storeId: null,
        regionId: null,
        userId: null,
        userName: null,
        avatar: null,
        sex: null,
        birthday: null,
        phoneNumber: null,
        status: null,
        openId: null,
        isDelete: null,
      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {},
      regionOption: [], // 区域下拉框
      storeOption: [], // 门店下拉框
      searchStoreOption: [],
      regionId: "",
      regionName: "",
      storeId: "",
      storeName: "",
      //预约时间
      pickerOptions: {
        shortcuts: [
          {
            text: "当月",
            onClick(picker) {
              const end = new Date();
              const start = new Date(end.getFullYear(), end.getMonth(), 1);
              picker.$emit("pick", [start, end]);
            },
          },
          {
            text: "上月",
            onClick(picker) {
              const end = new Date();
              const start = new Date();
              start.setMonth(start.getMonth() - 1); // 设置开始时间为上月同一天
              start.setDate(end.getDate()); // 确保开始时间和结束时间在同一天
              picker.$emit("pick", [start, end]);
            },
          },
          {
            text: "近三个月",
            onClick(picker) {
              const end = new Date();
              const start = new Date();
              start.setMonth(start.getMonth() - 3); // 设置开始时间为上月同一天
              start.setDate(end.getDate()); // 确保开始时间和结束时间在同一天
              picker.$emit("pick", [start, end]);
            },
          },
          {
            text: "近六个月",
            onClick(picker) {
              const end = new Date();
              const start = new Date();
              start.setMonth(start.getMonth() - 6); // 设置开始时间为上月同一天
              start.setDate(end.getDate()); // 确保开始时间和结束时间在同一天
              picker.$emit("pick", [start, end]);
            },
          },
        ],
      },
      time: [],
      type: "", //优惠券类型
    };
  },
  created() {
    this.getList();
    this.getRegionOption();
    this.type = this.$route.query.type;
  },
  methods: {
    /** 查询用户列表 */
    getList() {
      this.loading = true;
      listUser(this.queryParams).then((response) => {
        this.storeList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        storeId: null,
        regionId: null,
        id: null,
        userId: null,
        userName: null,
        avatar: null,
        sex: null,
        birthday: null,
        phoneNumber: null,
        status: null,
        openId: null,
        createTime: null,
        updateTime: null,
        isDelete: null,
      };
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
      this.time = [];
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map((item) => item.id);
      this.single = selection.length !== 1;
      this.multiple = !selection.length;
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.title = "添加用户";
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      const id = row.id || this.ids;
      getUser(id).then((response) => {
        this.form = response.data;
        this.open = true;
        this.title = "修改用户";
      });
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate((valid) => {
        if (valid) {
          if (this.form.id != null) {
            updateUser(this.form).then((response) => {
              this.$modal.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            });
          } else {
            addUser(this.form).then((response) => {
              this.$modal.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const ids = row.id || this.ids;
      this.$modal
        .confirm('是否确认删除用户编号为"' + ids + '"的数据项？')
        .then(function () {
          return delUser(ids);
        })
        .then(() => {
          this.getList();
          this.$modal.msgSuccess("删除成功");
        })
        .catch(() => {});
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download(
        "system/user/export",
        {
          ...this.queryParams,
        },
        `user_${new Date().getTime()}.xlsx`
      );
    },
    // 获取归属区域下拉数据
    getRegionOption() {
      fetchRegionList().then((res) => {
        this.regionOption = res.data.map((rItem) => {
          return {
            value: rItem.id,
            label: rItem.regionName,
          };
        });
      });
    },
    // 归属区域切换
    regionChange(value) {
      const selectedOption = this.regionOption.find(
        (item) => item.value === value
      );
      this.regionId = value;
      this.regionName = selectedOption.label;
      if (value) {
        this.queryParams.storeId = "";
      }
      fetchStoreList({ regionId: value }).then((res) => {
        this.storeOption = res.data.map((rItem) => {
          return {
            label: rItem.storeName,
            value: rItem.id,
          };
        });
      });
    },
    // 归属门店切换
    storeIdChange(value) {
      const selectedOption = this.storeOption.find(
        (item) => item.value === value
      );
      console.log("selectedOption", selectedOption, value, this.storeOption);
      this.storeId = value;
      this.queryParams.storeId = value;
      this.storeName = selectedOption.label;
    },
    searchRegionChange(value) {
      if (value) {
        this.queryParams.storeId = "";
      }
      fetchStoreList({ regionId: value }).then((res) => {
        this.searchStoreOption = res.data.map((rItem) => {
          return {
            label: rItem.storeName,
            value: rItem.id,
          };
        });
      });
    },
    getTime() {
      console.log(this.time, "time");
    },
  },
};
</script>
